# -*- coding: utf-8 -*-
"""
增强的Agent工具处理器，集成WorkbenchAgent的优秀功能
"""

import json
from typing import List, Dict, Any


class K8sResultFormatter:
    """K8s结果格式化器，从WorkbenchAgent移植过来"""

    @staticmethod
    def _extract_k8s_resource_info(resource: dict) -> dict:
        """专门处理K8s资源的信息提取"""
        result = {}

        # 基本信息
        result["Kind"] = resource.get("kind", "Unknown")
        result["APIVersion"] = resource.get("apiVersion", "Unknown")

        # Metadata信息
        metadata = resource.get("metadata", {})
        result["Name"] = metadata.get("name", "Unknown")
        result["Namespace"] = metadata.get("namespace", "default")
        result["CreationTime"] = metadata.get("creationTimestamp", "Unknown")

        # Pod特有信息
        if resource.get("kind") == "Pod":
            spec = resource.get("spec", {})
            status = resource.get("status", {})

            containers = spec.get("containers", [])
            if containers:
                container_names = [c.get("name", "unnamed") for c in containers]
                result["Containers"] = ", ".join(container_names[:3])
                if len(containers) > 3:
                    result["Containers"] += f" (+{len(containers) - 3} more)"

            result["Phase"] = status.get("phase", "Unknown")
            result["Node"] = spec.get("nodeName", "Unknown")

            conditions = status.get("conditions", [])
            ready_condition = next(
                (c for c in conditions if c.get("type") == "Ready"), None
            )
            if ready_condition:
                result["Ready"] = ready_condition.get("status", "Unknown")

        # Service特有信息
        elif resource.get("kind") == "Service":
            spec = resource.get("spec", {})
            result["Type"] = spec.get("type", "Unknown")
            result["ClusterIP"] = spec.get("clusterIP", "Unknown")
            ports = spec.get("ports", [])
            if ports:
                port_info = [
                    f"{p.get('port', 'Unknown')}/{p.get('protocol', 'TCP')}"
                    for p in ports[:2]
                ]
                result["Ports"] = ", ".join(port_info)

        return result

    @staticmethod
    def format_json_to_markdown_table(data: List[dict], max_rows: int = 15) -> str:
        """优化的表格格式化"""
        if not data:
            return "没有找到任何条目。"

        summary_message = ""
        display_data = data[:max_rows]

        if len(data) > max_rows:
            summary_message = f"总共 {len(data)} 条，显示前 {max_rows} 条。\n\n"

        # 预处理数据
        processed_data = []
        for item in display_data:
            if isinstance(item, dict):
                if "kind" in item and "metadata" in item:
                    processed_item = K8sResultFormatter._extract_k8s_resource_info(item)
                else:
                    processed_item = item
                processed_data.append(processed_item)
            else:
                processed_data.append({"Value": str(item)})

        if not processed_data:
            return summary_message + "数据处理后为空。"

        # 获取表头
        all_headers = set()
        for item in processed_data:
            all_headers.update(item.keys())

        priority_headers = [
            "Name",
            "Kind",
            "Namespace",
            "Phase",
            "Ready",
            "Containers",
            "Node",
            "Type",
            "ClusterIP",
        ]
        headers = []

        for header in priority_headers:
            if header in all_headers:
                headers.append(header)
                all_headers.remove(header)

        remaining_headers = sorted(list(all_headers))
        headers.extend(remaining_headers[: max(0, 10 - len(headers))])

        # 构建表格
        header_row = "| " + " | ".join(headers) + " |"
        separator_row = "| " + " | ".join(["---"] * len(headers)) + " |"

        data_rows = []
        for item in processed_data:
            row_values = []
            for header in headers:
                value = str(item.get(header, ""))
                value = value.replace("\n", " ").replace("\r", " ").replace("|", "\\|")
                if len(value) > 80:
                    value = value[:77] + "..."
                row_values.append(value)
            data_rows.append("| " + " | ".join(row_values) + " |")

        table_content = "\n".join([header_row, separator_row] + data_rows)
        return summary_message + table_content


class TokenManager:
    """Token管理器，防止上下文溢出"""

    def __init__(
        self, max_tool_result_length: int = 800, max_total_tokens: int = 50000
    ):
        self.max_tool_result_length = max_tool_result_length
        self.max_total_tokens = max_total_tokens

    def truncate_content(self, content: str, max_length: int = None) -> str:
        """智能截断内容"""
        if max_length is None:
            max_length = self.max_tool_result_length

        if len(content) <= max_length:
            return content

        truncated = content[:max_length]
        last_sentence = truncated.rfind("。")
        last_period = truncated.rfind(".")
        last_newline = truncated.rfind("\n")

        cut_point = max(last_sentence, last_period, last_newline)
        if cut_point > max_length * 0.8:
            truncated = content[: cut_point + 1]

        return truncated + f"\n... (内容已截断，原长度: {len(content)} 字符)"
